/**
 * Adspace Size Cascade.
 */
define(['jquery', 'listAsyncOp','bootstrap-dialog'], function($, VamListOp, BootstrapDialog) {
	var AdspaceSizeCascade;
	AdspaceSizeCascade = (function() {
		function AdspaceSizeCascade() {
		}

		AdspaceSizeCascade.prototype.init = function() {
			this.pageUrlInit();
			this.adspaceSizeCascade();
			this.customSizeCascade();
			this.pageOccupation();
			this.adForamtTips();
			this.codePreview();
		};
		AdspaceSizeCascade.prototype.pageUrlInit = function() {
			$("input[name=container]").on('click',function() {
	      var $me = $(this);
	      if ($me.val() === "2") {
	        $('#page_url').val("");
	        $('#pageURL').show();
	      } else {
	        $('#page_url').val("http://aout.com");
	        $('#pageURL').hide();
	      }
	    });
		};
		AdspaceSizeCascade.prototype.adspaceSizeCascade = function() {
			// Adspace Size Cascade.
	    var standard = $.parseJSON(VAM.getVar('ADSPACE_SIZE')),
	    $adSpaceType1 = $('#adspace_phylum'),
	    $adSpaceType2 = $('#adspace_type'),
	    $adSize = $('#adspace_size'),
	    $customSize = $('#custom_adsize'),
	    $adWidth = $('#adspace_width'),
	    $adHeight = $('#adspace_height'),
	    $putSize = $('#put_adsize'),
	    $putSizeSelect = $('#put_adsize_select');
	    for (var key in standard){
	      if(standard.hasOwnProperty(key)){
	        $adSpaceType1.append('<option value="'+ key + '">' + key + '</option>');
	      }
	    }
	    $adSpaceType1.on('change',function(){
	      var $me=$(this),
	        type = standard[$me.val()];
	      $adSpaceType2.children().remove();
	      for(var key in type){
	        if (type.hasOwnProperty(key)){
	          $adSpaceType2.append('<option value="' + key + '">' + key + '</option>');
	        }
	      }
	      if ($me.val() === "PC 弹窗广告"){
	        $('#full_media_order').removeClass('vam-hidden');
	      }else{
	        $('#full_media_order').addClass('vam-hidden');
	      }
	      $adSpaceType2.trigger('change');
	    });
	    $adSpaceType1.trigger('change');
	    $adSpaceType2.on('change',function(){
	      var $me = $(this),
	        size = standard[$adSpaceType1.val()][$me.val()],
	        i,l;
	      $adSize.children().remove();

	      for(i = 0, l = size.length; i < l; i++) {
	        $adSize.append('<option value="' + size[i] + '">' + size[i] + '</option>');
	      }
	      $adSize.append('<option value="自定义">自定义</option>');
	      $customSize.hide();
	      $putSize.hide();
	      $adSize.trigger('change');
	    });
	    $adSpaceType2.trigger('change');
	    $adSize.on('change',function(){
	      var $me = $(this);
	      if ($me.val() == '自定义') {
	        $adWidth.val('');
	        $adHeight.val('');
	        $customSize.show();
	        $putSizeSelect.children().remove();
	        $putSize.show();
	      } else {
	        $adWidth.val($adSize.val().split('*')[0]);
	        $adHeight.val($adSize.val().split('*')[1]);
	        $customSize.hide();
	        $putSizeSelect.children().remove();
	        $putSizeSelect.append('<option value="' + $adSize.val() + '">' + $adSize.val() + '</option>');
	          $putSize.hide();
	      }
	    });
	    $adSize.trigger('change');
		};
		AdspaceSizeCascade.prototype.customSizeCascade = function() {
			// Custom size handle.
	    var adSpaceStandard = $.parseJSON(VAM.getVar('ADSPACE_SIZE')),
	      $adWidthInput = $('#adspace_width'),
	      $adWidthInputError = $('#width_err'),
	      $adHeightInput = $('#adspace_height'),
	      $adHeightInputError = $('#height_err'),
	      $putSizeSelect = $('#put_adsize_select'),
	      i, _len, _w, _h, sortStandardSize, putSizeList = [], putSizeListTemp = [], 
	      renderPutSizeSelect, changeAdspaceType;
	    sortStandardSize = function(a,b) {
	      if (b.width > a.width) {
	        return 1;
	      } else if (b.width < a.width) {
	        return -1;
	      } else {
	        return b.height - a.height;
	      }
	    };
	      
	    changeAdspaceType = function(customAdSize) {
	      var adTypeObj={}, i, l, 
	        adSpaceType1 = $('#adspace_phylum').val(), adSpaceType2;
	      for (adSpaceType2 in adSpaceStandard[adSpaceType1]) {
	        if (adSpaceStandard[adSpaceType1].hasOwnProperty(adSpaceType2)) {
	          for (var m = 0,n = adSpaceStandard[adSpaceType1][adSpaceType2].length; m < n; m++) {
	            if (adSpaceStandard[adSpaceType1][adSpaceType2][m] === customAdSize) {
	              adTypeObj.type2 = adSpaceType2;
	              adTypeObj.size = customAdSize;
	            }
	          }
	        }
	      }
	      for (i = 0,l = $('#adspace_type option').length; i < l; i++) {
	        if($('#adspace_type option')[i].value === adTypeObj.type2) {
	            $('#adspace_type option').eq(i).attr("selected", true);
	            break;
	        }
	      }
	    };

	    renderPutSizeSelect = function(){
	      var customWidth=parseInt($adWidthInput.val(),10),
	        customHeight=parseInt($adHeightInput.val(),10),
	        _i,_l=putSizeList.length;

	      if($adWidthInput.val() !== '' && $adWidthInputError.text() === '' && $adHeightInput.val() !== '' && $adHeightInputError.text() === '') {
	        // 当填写正确时，先清空投放尺寸下拉框，选  框
	        $putSizeSelect.children().remove();
	        $putSizeSelect.attr("disabled",true);
	        for (_i = 0; _i < _l; _i++){
	          if(customWidth >= putSizeList[_i].width && customHeight >= putSizeList[_i].height){
	            $putSizeSelect.append('<option value="' + putSizeList[_i].width + '*' + putSizeList[_i].height + '">' + putSizeList[_i].width + '*' + putSizeList[_i].height + '</option>');
	          }
	        }
	        $putSizeSelect.append('<option value="' + customWidth + '*' + customHeight + '">实际尺寸</option>');

	        $putSizeSelect.attr("disabled",false);
	        // 标准硬广，如果填写的尺寸为标准尺寸，则选中对应的广告形式和尺寸
	        changeAdspaceType($adWidthInput.val() + '*' + $adHeightInput.val());
	      }else{
	        // 否则，清空投放尺寸下拉框，并禁用
	        $putSizeSelect.children().remove();
	        $putSizeSelect.attr("disabled",true);
	      }
	    };

	    // List all standard size.
	    for (var adSpaceType1 in adSpaceStandard) {
	      if (adSpaceStandard.hasOwnProperty(adSpaceType1)) {
	        for (var adSpaceType2 in adSpaceStandard[adSpaceType1]) {
	          if (adSpaceStandard[adSpaceType1].hasOwnProperty(adSpaceType2) && adSpaceType2 !== '文字链广告') {
	            for (i = 0, _len = adSpaceStandard[adSpaceType1][adSpaceType2].length; i < _len; i++) {
	              _w = adSpaceStandard[adSpaceType1][adSpaceType2][i].split('*')[0],
	              _h = adSpaceStandard[adSpaceType1][adSpaceType2][i].split('*')[1];
	              if(_w !== null && _h !== null){
	                putSizeList.push({
	                  "width":_w,
	                  "height":_h
	                });
	              }
	            }
	          }
	        }
	      }
	    }

	    // Sort all standard size.
	    putSizeList.sort(sortStandardSize);
	    // 对标准尺寸list进行去重
	    for ( i = 0, _len = putSizeList.length; i< _len; i++) {
	      if (putSizeList[i+1] !== undefined && putSizeList[i].width === putSizeList[i+1].width && putSizeList[i].height === putSizeList[i+1].height) {
	      } else {
	        putSizeListTemp.push(putSizeList[i]);
	      }
	    }
	    putSizeList = putSizeListTemp;

	    // 对自定义尺寸宽和高绑定事件，当高和宽填写完成验证无误时，对投放尺寸下拉框进行渲染
	    $adWidthInput.on('blur',function(){
	      window.setTimeout(renderPutSizeSelect,100);
	    });
	    $adHeightInput.on('blur',function(){
	      window.setTimeout(renderPutSizeSelect,100);
	    });
		};
		AdspaceSizeCascade.prototype.pageOccupation = function() {
			// Page Occcupation.
	    var occupation_classification = $.parseJSON(VAM.getVar('PAGE_OCCUPATION')),
	      $pageBig = $('#page_big'),
	      $pageSmall = $('#page_small');
	    for(var key in occupation_classification){
	      if(occupation_classification.hasOwnProperty(key)) {
	        $pageBig.append('<option value="' + key + '">' + key + '</option>');
	      }
	    }
	    $pageBig.on('change',function(){
	      var me = $(this),
	        page_small = occupation_classification[me.val()],
	        i,j;
	      $pageSmall.children().remove();
	      $pageSmall.append('<option value="全部小类">全部小类</option>');
	      for (i = 0, j = page_small.length; i < j; i++) {
	        $pageSmall.append('<option value="' + page_small[i] + '">' + page_small[i] +'</option>');
	      }
	    });
	    $pageBig.trigger('change');
		};
		AdspaceSizeCascade.prototype.adForamtTips = function() {
			$('#ad_format_cont input[type="checkbox"]').on('click', function() {
	      (!$('#ad_format_cont').find('input:checked').length) ? $('#ad_type').val('').trigger('blur') : $('#ad_type').val('selectedAdType').trigger('blur');
	    });
		};
		AdspaceSizeCascade.prototype.codePreview = function() {
			var $defaultCodeShow = $('#default_show_btn'),
	      dataPreviewCodeOp = VAM.getVar('DATA_CODE_PREVIEW');
	    $defaultCodeShow.on('click', function(evt) {
	      var previewCode = $('#creative_code').val();
	      VamListOp.listOp({
	        url: dataPreviewCodeOp,
	        data: {
	          code: previewCode
	        },
	        success: function(data) {
	          BootstrapDialog.show({
	            title: '代码预览',
	            type: BootstrapDialog.TYPE_INFO,
	            size: BootstrapDialog.SIZE_WIDE,
	            message: $('<iframe class="code-preview" style="width:100%;height:500px;border:0;" src="' + data.url + '"></iframe>'),
	            buttons: [{
	              label: '关闭',
	              cssClass: 'btn-default',
	              action: function(dialogItself) {
	                dialogItself.close();
	              }
	            }]
	          });
	        },
	        always: function() {}
	      });
	    });
		};

		return AdspaceSizeCascade;
	})();

	return new AdspaceSizeCascade();
});